"use client";

import { useEffect, useState } from "react";

export function ReadingProgress() {
  const [progress, setProgress] = useState(0);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    const updateProgress = () => {
      if (typeof window === 'undefined') return;
      
      const article = document.querySelector('article');
      if (article) {
        const articleHeight = article.offsetHeight;
        const windowHeight = window.innerHeight;
        const scrollPosition = window.scrollY;
        const totalScrollable = articleHeight - windowHeight;
        
        if (totalScrollable > 0) {
          const currentProgress = (scrollPosition / totalScrollable) * 100;
          setProgress(Math.min(100, Math.max(0, currentProgress)));
        } else {
          setProgress(100);
        }
      }
    };

    // 初始化进度值
    updateProgress();
    window.addEventListener('scroll', updateProgress);
    window.addEventListener('resize', updateProgress);
    
    return () => {
      window.removeEventListener('scroll', updateProgress);
      window.removeEventListener('resize', updateProgress);
    };
  }, []);

  if (!mounted) return null;

  return (
    <div className="fixed top-0 left-0 w-full h-1 bg-white/10 z-50">
      <div
        className="h-full bg-emerald-400/80 transition-all duration-150"
        style={{ width: `${progress}%` }}
      />
    </div>
  );
}